loadCustom({
    selector: '[data-banner]', defaultPath: 'banner.html', callback: (container) => {
        loadBannerComponent(container);
    }
});

function loadBannerComponent(container) {
    const template = document.getElementById("banner-template");
    const clone = template.content.cloneNode(true);
    const banner = clone.querySelector(".banner");
    const ul = clone.querySelector(".bd");
    const images = container.dataset.images.split(",");

    // 添加图片项
    images.forEach((img, index) => {
        const li = document.createElement("li");
        li.style.backgroundImage = `url(${img.trim()})`;
        if (index === 0) li.classList.add("active");
        ul.appendChild(li);
    });

    // ✅ 确保 DOM 构建完再获取
    const lis = ul.querySelectorAll("li");
    let current = 0;

    function show(index) {
        lis.forEach((li, i) => {
            li.classList.toggle("active", i === index);
        });
    }

    clone.querySelector(".prev").onclick = () => {
        current = (current - 1 + lis.length) % lis.length;
        show(current);
    };
    clone.querySelector(".next").onclick = () => {
        current = (current + 1) % lis.length;
        show(current);
    };


    let timer = null;
    let isPageVisible = true;
    function startAutoPlay() {
        if (timer) clearInterval(timer);
        timer = setInterval(() => {
            if (!isPageVisible) return;
            current = (current + 1) % lis.length;
            show(current);
        }, 2000);
    }

    // 页面可见性监听
    document.addEventListener("visibilitychange", () => {
        isPageVisible = document.visibilityState === "visible";
        if (isPageVisible) {
            startAutoPlay();
        } else {
            clearInterval(timer);
        }
    });

    banner.addEventListener("mouseenter", () => clearInterval(timer));
    banner.addEventListener("mouseleave", () => startAutoPlay());
    startAutoPlay();
    container.appendChild(clone);
}
